package com.itstyle.seckill.common.algorithm;

/**
 * @Auther: liuwenxiang
 * @Date: 2020/3/10 23:52
 * @Description:
 */
public class alTest {

    public static void main(String[] args) {
        System.out.println(5/2);
        int[] arr = {4, 35, 6, 1, 5, 7};
        sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        int x = find(arr, 6);
        System.out.println(x);
    }


    public static void sort(int[] list) {
        for (int i = 0; i < list.length - 1; i++) {//比较的轮次--list.length-1是因为n个元素，有n-1个有序两，第n个自然有序
            for (int j = 0; j < list.length - 1 - i; j++) {//每轮比较的次数--list.length-1-i减i，是因为每一轮少一个需要排序的元素
                if (list[j] > list[j + 1]) {
                    int temp = list[j];
                    list[j] = list[j + 1];
                    list[j + 1] = temp;
                }
            }
        }
    }

    public static int find(int[] list, int n) {
        int min = 0;
        int max = list.length - 1;
        while (min <= max) {//等号是数组只有一个元素的时候
            int middle = (min + max) / 2;
            if (n < list[middle]) {
                max = middle - 1;
            } else if (n > list[middle]) {
                min = middle + 1;
            } else {
                return middle+1;//获取到下表+1，才是数字的位置
            }
        }
        return -1;//没有匹配到
    }

    private static int binarySearch(int[] arr, int start, int end, int key) {

        if (key < arr[start] || key > arr[end] || start > end) { //start > end 不能为'>='
            return -1;
        }

        int mid = (start + end) / 2;
        if (key > arr[mid]) {
            return binarySearch(arr, mid + 1, end, key);
        } else if (key < arr[mid]) {
            return binarySearch(arr, start, mid - 1, key);
        } else {
            return mid + 1;
        }


    }
}